//
//  LoginViewController.m
//  SuperRadio
//
//  Created by GYRu on 14-12-29.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "LoginViewController.h"
#import "WeiboSDK.h"
#import "MyCollectViewController.h"
#import "ClearViewController.h"
#import "AboutUsViewController.h"
#import "NetHandler.h"
#import "WeiboLogin.h"
#import "UIImageView+WebCache.h"
#import "UIColor+AddColor.h"

#import "DataBaseHandler.h"
#import "AppDelegate.h"

#define kAppKey  @"2896537712"
#define kRedirectURI @"http://www.sina.com"


@interface LoginViewController ()<UIAlertViewDelegate, WBHttpRequestDelegate>


@property(nonatomic, retain)WeiboLogin *daxieLogin;
// 用户的头像
@property(nonatomic, retain)UIImageView *weiboPhoto;
// 登录用户名
@property(nonatomic, retain)UILabel *nameLable;
// 登陆前的提示图像
@property(nonatomic, retain)UIImageView *touxiang;
// 登录按钮
@property (nonatomic, retain) UIButton *login;
//
@property (nonatomic, retain) UIButton *share;

// 判断是否登录
@property (nonatomic, assign) BOOL successLogin;

@end

@implementation LoginViewController

#pragma mark 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        // 通知中心
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        // 增加一个观察者
        [center addObserver:self selector:@selector(recetiveNotification:) name:@"changeColor" object:nil];
        
        
        
//        // 通知中心
//        NSNotificationCenter *collectFication = [NSNotificationCenter defaultCenter];
//        // 增加一个观察者
//        [collectFication addObserver:self selector:@selector(collectFication:) name:@"chenggong" object:nil];
//        
//        self.successLogin = NO;
        
        
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(zhuxiao:)];
    self.navigationItem.rightBarButtonItem = nil;
    
   
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#f6f5ec"];
    
    
    
    // 登录的背景图片
    UIImageView *header = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, 64, self.view.frame.size.width, self.view.frame.size.height / 3)];
    //header.backgroundColor = [UIColor magentaColor];
    header.image = [UIImage imageNamed:@"denglubj.jpg"];
    [self.view addSubview:header];
    header.userInteractionEnabled = YES;
    [header release];
    
    
    self.touxiang = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/6, 80, 80)];
    self.touxiang.image = [UIImage imageNamed:@"tishi.png"];
    self.touxiang.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 - 30);
    [header addSubview:self.touxiang];
    [_touxiang release];
    
    
    
    
    
//    //显示登陆后的头像
    self.weiboPhoto  = [[UIImageView alloc]initWithFrame:CGRectMake(110, 60, 80, 80)];
    [header addSubview:self.weiboPhoto];
    self.weiboPhoto.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 - 30);
    //self.weiboPhoto.backgroundColor = [UIColor cyanColor];
    //让头像变成圆的
     self.weiboPhoto.clipsToBounds = YES;
    self.weiboPhoto.layer.cornerRadius = 40;
    [_weiboPhoto release];
    
    
    //显示博主名字
    self.nameLable = [[UILabel alloc]initWithFrame:CGRectMake(10, self.view.frame.size.height * 140 / 667,self.view.frame.size.width * 300 / 375, self.view.frame.size.height * 40 / 667)];
    self.nameLable.tintColor = [UIColor blackColor];
    self.nameLable.textAlignment = 1;
    self.nameLable.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 + 40);
    [header addSubview:self.nameLable];
    [_nameLable release];
    
    
    
    
    
    // 登陆按钮
    self.login = [UIButton buttonWithType:UIButtonTypeSystem];
    self.login.frame = CGRectMake(self.view.frame.size.width * 260 / 375, self.view.frame.size.height * 140 / 667, self.view.frame.size.width * 100 / 375, self.view.frame.size.height * 40 / 667);
    self.login.tintColor = [UIColor blackColor];
    //self.login.backgroundColor = [UIColor yellowColor];
    [self.login setTitle:@"请登录" forState:UIControlStateNormal];
    self.login.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/6 + 40);
    // 给登录按钮一个方法
    [self.login addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    // 将登陆按钮添加到header上
    [header addSubview:self.login];
    
    
    
    // 我的收藏按钮
    UIButton *collect = [UIButton buttonWithType:UIButtonTypeSystem];
    collect.frame = CGRectMake(self.view.frame.size.width * 30 / 375, self.view.frame.size.height * 310 / 667, self.view.frame.size.width * 315 / 375, self.view.frame.size.height * 45 / 667);
    collect.backgroundColor = [UIColor whiteColor];
    collect.alpha = 0.8;
    // 我的收藏按钮添加方法
    [collect addTarget:self action:@selector(myCollect:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:collect];
    
    // 在我的收藏按钮上添加收藏图标
    UIImageView *collectImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 10 / 375, self.view.frame.size.height * 7 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
    // 给收藏图片赋值
    NSString *collPath = [[NSBundle mainBundle] pathForResource:@"woshoucang" ofType:@"png"];
    collectImage.image = [UIImage imageWithContentsOfFile:collPath];
    // 将图标添加到我的收藏按钮上
    [collect addSubview:collectImage];
    [collectImage release];
    
    // 添加标题
    UILabel *collectTitle = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 50 / 375, self.view.frame.size.height * 6 / 667, self.view.frame.size.width * 200 / 375, self.view.frame.size.width * 30 / 375)];
    // 设置标题text
    collectTitle.text = @"我的收藏";
    collectTitle.textAlignment = NSTextAlignmentLeft;
    collectTitle.font = [UIFont fontWithName:@"KaiTi_GB2312" size:18];
    // 将标题添加到我的收藏按钮上
    [collect addSubview:collectTitle];
    [collectTitle release];
    
    
    // 在我的收藏按钮上添加进入图标
    UIImageView *collImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 290 / 375, self.view.frame.size.height * 8 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
    // 给图片赋值
    NSString *coPath = [[NSBundle mainBundle] pathForResource:@"jinru" ofType:@"png"];
    collImage.image = [UIImage imageWithContentsOfFile:coPath];
    // 将图标添加到我的收藏按钮上
    [collect addSubview:collImage];
    [collImage release];
    
    
    
    // 清除缓存按钮
    UIButton *clear = [UIButton buttonWithType:UIButtonTypeSystem];
    clear.frame = CGRectMake(self.view.frame.size.width * 30 / 375, self.view.frame.size.height * 375 / 667, self.view.frame.size.width * 315 / 375, self.view.frame.size.height * 45 / 667);
    clear.backgroundColor = [UIColor whiteColor];
    clear.alpha = 0.8;
    [clear addTarget:self action:@selector(clearClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clear];
    
    
    // 在清除按钮上添加清除图标
    UIImageView *clearImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 10 / 375, self.view.frame.size.height * 7 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
    // 给清除图片赋值
    NSString *clearPath = [[NSBundle mainBundle] pathForResource:@"shanchu" ofType:@"png"];
    clearImage.image = [UIImage imageWithContentsOfFile:clearPath];
    // 将图标添加到清除按钮上
    [clear addSubview:clearImage];
    [clearImage release];
    
    // 添加标题
    UILabel *clearTitle = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 50 / 375, self.view.frame.size.height * 6 / 667, self.view.frame.size.width * 200 / 375, self.view.frame.size.width * 30 / 375)];
    // 设置标题text
    clearTitle.text = @"清除缓存";
    clearTitle.textAlignment = NSTextAlignmentLeft;
    clearTitle.font = [UIFont fontWithName:@"KaiTi_GB2312" size:18];
    // 将标题添加到清除按钮上
    [clear addSubview:clearTitle];
    [clearTitle release];
    
    // 在清除按钮上添加进入图标
    UIImageView *cleImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 290 / 375, self.view.frame.size.height * 8 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
    // 给图片赋值
    NSString *cPath = [[NSBundle mainBundle] pathForResource:@"jinru" ofType:@"png"];
    cleImage.image = [UIImage imageWithContentsOfFile:cPath];
    // 将图标添加到清除按钮上
    [clear addSubview:cleImage];
    [cleImage release];
    

    // 关于我们按钮
    UIButton *about = [UIButton buttonWithType:UIButtonTypeSystem];
    about.frame = CGRectMake(self.view.frame.size.width * 30 / 375, self.view.frame.size.height * 440 / 667, self.view.frame.size.width * 315 / 375, self.view.frame.size.height * 45 / 667);
    about.backgroundColor = [UIColor whiteColor];
    about.alpha = 0.8;
    [about addTarget:self action:@selector(aboutUsClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:about];
    
    // 在关于我们按钮上添加清除图标
    UIImageView *aboutImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 10 / 375, self.view.frame.size.height * 7 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
    // 给关于我们图片赋值
    NSString *aboutPath = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"png"];
    aboutImage.image = [UIImage imageWithContentsOfFile:aboutPath];
    // 将图标添加到关于我们按钮上
    [about addSubview:aboutImage];
    [aboutImage release];
    
    // 添加标题
    UILabel *aboutTitle = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 50 / 375, self.view.frame.size.height * 6 / 667, self.view.frame.size.width * 200 / 375, self.view.frame.size.width * 30 / 375)];
    // 设置标题text
    aboutTitle.text = @"关于我们";
    aboutTitle.textAlignment = NSTextAlignmentLeft;
    aboutTitle.font = [UIFont fontWithName:@"KaiTi_GB2312" size:18];
    // 将标题添加到关于我们按钮上
    [about addSubview:aboutTitle];
    [aboutTitle release];
    
    
    // 在关于我们按钮上添加进入图标
    UIImageView *abImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 290 / 375, self.view.frame.size.height * 8 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
    // 给图片赋值
    NSString *abPath = [[NSBundle mainBundle] pathForResource:@"jinru" ofType:@"png"];
    abImage.image = [UIImage imageWithContentsOfFile:abPath];
    // 将图标添加到关于我们按钮上
    [about addSubview:abImage];
    [abImage release];
    
    
    
//    // 关于我们按钮
//    UIButton *downLoad = [UIButton buttonWithType:UIButtonTypeSystem];
//    downLoad.frame = CGRectMake(self.view.frame.size.width * 30 / 375, self.view.frame.size.height * 505 / 667, self.view.frame.size.width * 315 / 375, self.view.frame.size.height * 45 / 667);
//    downLoad.backgroundColor = [UIColor whiteColor];
//    downLoad.alpha = 0.8;
//    [downLoad addTarget:self action:@selector(aboutUsClick:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:downLoad];
//    
//    // 在关于我们按钮上添加清除图标
//    UIImageView *downLoadImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 10 / 375, self.view.frame.size.height * 7 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
//    // 给关于我们图片赋值
//    NSString *downLoadPath = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"png"];
//    downLoadImage.image = [UIImage imageWithContentsOfFile:downLoadPath];
//    // 将图标添加到关于我们按钮上
//    [downLoad addSubview:downLoadImage];
//    [downLoadImage release];
//    
//    // 添加标题
//    UILabel *downLoadTitle = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 50 / 375, self.view.frame.size.height * 6 / 667, self.view.frame.size.width * 200 / 375, self.view.frame.size.width * 30 / 375)];
//    // 设置标题text
//    downLoadTitle.text = @"我的下载";
//    downLoadTitle.textAlignment = NSTextAlignmentLeft;
//    downLoadTitle.font = [UIFont fontWithName:@"KaiTi_GB2312" size:18];
//    // 将标题添加到关于我们按钮上
//    [downLoad addSubview:downLoadTitle];
//    [downLoadTitle release];
//    
//    
//    // 在关于我们按钮上添加进入图标
//    UIImageView *dlImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 290 / 375, self.view.frame.size.height * 8 / 667, self.view.frame.size.width * 25 / 375, self.view.frame.size.width * 25 / 375)];
//    // 给图片赋值
//    NSString *dlPath = [[NSBundle mainBundle] pathForResource:@"jinru" ofType:@"png"];
//    dlImage.image = [UIImage imageWithContentsOfFile:dlPath];
//    // 将图标添加到关于我们按钮上
//    [downLoad addSubview:dlImage];
//    [dlImage release];

    
    
}

#pragma mark 登陆按钮(微博登陆)的方法
- (void)loginClick:(UIButton *)button
{
    
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURI;
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
    
    
}

#pragma mark 登录时接到通知中心执行的方法
- (void)recetiveNotification:(NSNotification *)noti
{
    // 一接收到消息通知 立即执行的内容

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(zhuxiao:)];

    self.login.hidden = YES;
    self.touxiang.hidden = YES;

    NSString *str = [noti.userInfo objectForKey:@"access_token"];
    NSNumber *number = [noti.userInfo objectForKey:@"uid"];
    
    
    NSString *meshStr = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@", [number description], str];
    NSLog(@"%@",meshStr);
    
    [NetHandler getDataWithURL:meshStr completion:^(NSData *data) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       
        self.daxieLogin = [[WeiboLogin alloc] initWithDictionary:resultDic];
        
        [_daxieLogin release];
        // 获取微博昵称
        self.nameLable.text = self.daxieLogin.screen_name;
//        self.guanzhuLable.text = [self.daxieLogin.friends_count description];
//        self.fansLable.text = [self.daxieLogin.followers_count description];
//        self.weiboShuLable.text = [self.daxieLogin.statuses_count description];
        [self.weiboPhoto setImageWithURL:[NSURL URLWithString:self.daxieLogin.avatar_hd]];
        // 不隐藏微博头像和昵称
        self.weiboPhoto.hidden = NO;
        self.nameLable.hidden = NO;
        NSLog(@"%@=====",self.daxieLogin.avatar_hd);
    }];
        
    
    
}


#pragma mark 注销按钮方法
- (void)zhuxiao:(UIBarButtonItem *)noti
{
    // 点击注销会弹出是否注销的框
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定注销吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    [alert release];
    // 设置alert的tag值为999
    alert.tag = 999;
   
}

#pragma mark 注销按钮点击方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 当tag值为999时
    if (alertView.tag == 999) {
        
        switch (buttonIndex) {
            // 如果点击的下标为1
            case 1:
            {
                // 执行微博注销方法
                AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
                [WeiboSDK logOutWithToken:myDelegate.wbtoken delegate:self withTag:@"user1"];
                
                //延时调用  一秒以后执行
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    // 隐藏 登录和默认头像
                    self.login.hidden = NO;
                    self.touxiang.hidden = NO;
                    // 让navigationItem右侧按钮为空
                    self.navigationItem.rightBarButtonItem = nil;
                    // 将微博头像和微博名字显示
                    self.weiboPhoto.hidden = YES;
                    self.nameLable.hidden = YES;
                    
//                    // 在注销的同时关闭数据库
//                    DataBaseHandler *handler = [DataBaseHandler shareInstance];
//                    [handler closeDB];
//                    // 注销时使登录状态变为no
//                    self.successLogin = NO;
                    
                });
            }
                break;
                
            default:
                break;
        }
    }

}

#pragma mark -
#pragma WBHttpRequestDelegate

- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    // 在注销成功的时候会弹出注销成功的框
    NSString *title = nil;
    UIAlertView *alert = nil;
    
//    title = NSLocalizedString(@"收到网络回调", nil);
//    alert = [[UIAlertView alloc] initWithTitle:title
//                                       message:[NSString stringWithFormat:@"%@",result]
//                                      delegate:nil
//                             cancelButtonTitle:NSLocalizedString(@"确定", nil)
//                             otherButtonTitles:nil];
    title = NSLocalizedString(@"注销成功", nil);
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:nil
                                      delegate:nil
                             cancelButtonTitle:NSLocalizedString(@"确定", nil)
                             otherButtonTitles:nil];
    [alert show];
    [alert release];
}


#pragma mark 进入我的收藏
- (void)myCollect:(UIButton *)collect
{
    DataBaseHandler *handler = [DataBaseHandler shareInstance];
    // 打开数据库
    [handler openDB];
    // 点击将进入我的收藏那页
    MyCollectViewController *myCollectVC = [[MyCollectViewController alloc] init];
//    if ([handler selectAll] == NO) {
//        // 如果搜索内容为空 则提示
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"收藏内容为空,请先收藏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//        [alert show];
//        [alert release];
//    } else {
    
        [self.navigationController pushViewController:myCollectVC animated:YES];
        
//    }

    [myCollectVC release];
    
}


//#pragma mark 收藏时通知中心要执行的方法
//- (void)collectFication:(NSNotification *)fication
//{
//    // 当接到通知则显示登录状态为yes
//    self.successLogin = YES;
//    
//}




#pragma mark 进入清除缓存
- (void)clearClick:(UIButton *)clear
{
    
    ClearViewController *clearVC = [[ClearViewController alloc] init];
    // push推出清除缓存页面
    [self.navigationController pushViewController:clearVC animated:YES];
    [clearVC release];
}


#pragma mark 进入关于我们
- (void)aboutUsClick:(UIButton *)about
{
    
    AboutUsViewController *aboutVC = [[AboutUsViewController alloc] init];
    // push推出清除缓存
    [self.navigationController pushViewController:aboutVC animated:YES];
    [aboutVC release];
}



- (void)dealloc
{
    [_daxieLogin release];
    [_weiboPhoto release];
    [_nameLable release];
    [_touxiang release];
    [_login release];
    [_share release];
    [_myCollect release];
    
    [super dealloc];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
